package com.springboot.wisdom.mqtt.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.integration.channel.DirectChannel;
import org.springframework.integration.mqtt.core.MqttPahoClientFactory;
import org.springframework.integration.mqtt.outbound.MqttPahoMessageHandler;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.MessageHandler;

@Configuration
public class MqttOutboundConfiguration {

    @Autowired
    public MqttConfigurationProperties mqttConfigurationProperties;

    @Autowired
    private MqttPahoClientFactory mqttPahoClientFactory;

    /**
     * 消息通道。
     */
    @Bean
    public MessageChannel messageOutboundChannel() {
        return new DirectChannel();
    }

    /**
     * 配置出站适配器，设置发布的主题，以及指定消息的相关属性。
     *
     * @return
     */
    @Bean
    @ServiceActivator(inputChannel = "messageOutboundChannel")
    public MessageHandler mqttOutboundMessageHandler() {
        MqttPahoMessageHandler mqttPahoMessageHandler = new MqttPahoMessageHandler(mqttConfigurationProperties.getUrl()
                , mqttConfigurationProperties.getPubClientId()
                , mqttPahoClientFactory);
        mqttPahoMessageHandler.setDefaultQos(0);
//        mqttPahoMessageHandler.setDefaultTopic("default");
        mqttPahoMessageHandler.setDefaultTopic(mqttConfigurationProperties.getDefaultPubTopic());
        mqttPahoMessageHandler.setAsync(true);
        return mqttPahoMessageHandler;
    }
}
